package com.javabasic.serialize.deserializer;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.core.TreeNode;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.javabasic.serialize.model.Sex;
import com.javabasic.serialize.model.User;

import java.io.IOException;

/**
 * @Author: mir_xiong
 * @Title: UserDeserializer
 * @ProjectName: javabasic
 * @Description:
 * @Date: 2022/4/2 17:45
 */
public class UserDeserializer extends StdDeserializer<User> {

    public UserDeserializer() {
        super(User.class);
    }



    @Override
    public User deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        User user = new User();

        while (!jsonParser.isClosed()) {
            JsonToken jsonToken = jsonParser.nextToken();

            if (JsonToken.FIELD_NAME.equals(jsonToken)) {
                String currentFiledName = jsonParser.getCurrentName();

                jsonToken = jsonParser.nextToken();

                if ("userName".equals(currentFiledName)) {
                    user.setUserName(jsonParser.getValueAsString());
                } else if ("Class".equals(currentFiledName)) {
                    System.out.println("Class == " + jsonParser.getValueAsString());
                } else if ("age".equals(currentFiledName)) {
                    user.setAge(jsonParser.getValueAsInt());
                } else if ("Sex".equals(currentFiledName)) {
                    Sex sex = Sex.valueOf(jsonParser.getValueAsString());
                    user.setSex(sex);
                }
            }
        }
        return user;
    }
}
